home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-04
/
prolog_2.zip
/
PUZZLES.ZIP
/
MERGESRT.PRO
< prev
next >
Wrap
Text File
|
1987-05-19
|
1KB
|
39 lines
/*
program for merge sort by John Sun: Runtime O(n log n)
mergesort(Unsorted_List, Sorted_List) :-
Sorted_List is a list of sorted integers in ascending order sorted
using merge sort of the Unsorted_List.
To give this program a try use ?-mergesort([10,5,8,7,2,1,3,4,6,9], X).
Prolog should answer with: X = [1,2,3,4,5,6,7,8,9,10]
*/
mergesort([], []).
mergesort([X], [X]).
mergesort([X|Xs], Ys) :- Xs \= [],
mergesort([X], Ls),
mergesort( Xs, Rs),
!,
merge(Ls, Rs, Ys).
/*
merge(Xs, Ys, Zs) :-
Zs is an ordered list of integers obtained from merging
the ordered lists of integers Xs and Ys.
To give this merging predicate a try use ?-merge([1,3,5],[2,4,6],X).
*/
merge([X|Xs], [Y|Ys], [X|Zs]) :-
X < Y, !, merge(Xs, [Y|Ys], Zs).
merge([X|Xs], [Y|Ys], [X, Y|Zs]) :-
X = Y, !, merge(Xs, Ys, Zs).
merge([X|Xs], [Y|Ys], [Y|Zs]) :-
X > Y, !, merge([X|Xs], Ys, Zs).
merge(Xs, [], Xs) :- !.
merge([], Ys, Ys) :- !.